package com.gogowan.agroenterprise;

import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.ActivationInfo;
import com.gogowan.agroenterprise.model.CodeActivationInfo;
import com.gogowan.agroenterprise.model.CodeActivationResultInfo;
import com.gogowan.agroenterprise.model.MaterialBatch;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.utils.Utils;

/**
 * @author Maniac
 * @功能 激活指定号段的I-OID码
 * @描述 两次交互 1.在拍到起始截至码后执行交互获取批次列表 2.选择批次列表，激活。
 * @date 2012.11.16 增加输码形式获取
 */
public class ActivateActivity extends BaseActivity {

	private static int START = 1; // 调用拍码requestCode
	private static int END = 2;

	private Button takeStart; // 起始 拍码按钮
	private Button takeEnd; // 截止 拍码按钮
	// private Button getBtn; //当以输码形式输入时点击获取批次按钮
	private EditText startText; // 起始 I-OID显示
	private EditText endText; // 截止 I-OID显示
	private TextView materialName;
	/**
	 * 产品名称
	 */
	private LinearLayout layout;
	/**
	 * 一级批次
	 */
	private Spinner batch;
	/**
	 * 二级批次
	 */
	private Spinner batchsSec;
	/**
	 * 是否公共
	 */
	private Spinner isPublicOrSec;
	private boolean isPublic = true;

	private Button activateBtn; // 激活按钮
	private Button back; // 返回主页按钮
	private LinearLayout secLL; // 二级批次的布局
	/**
	 * 根列表
	 */
	private List<MaterialBatch> batches;
	/**
	 * 二级列表
	 */
	private List<MaterialBatch> batchesSec;
	private ProgressDialog progressDialog;

	private SharedPreferences sharedPreferences;
	private long enterpriseId = 0;
	private long materialId = 0;
	private long selectedBatch = 0;
	private long selectedBatchSecId = 0;
	private CodeActivationInfo requestBatchsInfo = new CodeActivationInfo();
	private boolean isNew;
	private String startCodStr;
	private String endCodStr;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activate);

		takeStart = (Button) findViewById(R.id.activate_start_btn);
		takeEnd = (Button) findViewById(R.id.activate_end_btn);
		// getBtn = (Button)findViewById(R.id.activate_get_btn);
		startText = (EditText) findViewById(R.id.activate_start_ed);
		endText = (EditText) findViewById(R.id.activate_end_ed);
		materialName = (TextView) findViewById(R.id.activate_material_name);
		layout = (LinearLayout) findViewById(R.id.activate_layout);

		batch = (Spinner) findViewById(R.id.activate_spinner);
		batchsSec = (Spinner) findViewById(R.id.activate_spinner_sec);
		secLL = (LinearLayout) findViewById(R.id.activate_secLL);
		isPublicOrSec = (Spinner) findViewById(R.id.activate_status);
		activateBtn = (Button) findViewById(R.id.activate_btn);
		back = (Button) findViewById(R.id.activate_cancel_btn);

		sharedPreferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		enterpriseId = sharedPreferences.getLong("enterpriseid", 0);
		isNew = sharedPreferences.getBoolean("isNew", false);

		takeStart.setOnClickListener(startPaima);
		takeEnd.setOnClickListener(endPaima);
		activateBtn.setOnClickListener(activateBatch);
		back.setOnClickListener(backToIndex);
		// getBtn.setOnClickListener(getBtnCallback);

		// 公共、子批次
		isPublicOrSec.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if (arg2 == 0) {
					isPublic = true;
					secLL.setVisibility(View.GONE);
				} else if (arg2 == 1) {
					isPublic = false;
					secLL.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

		batch.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				if (batches == null || batches.size() == 0) {
					showToast("一级列表List<MaterialBatch>为空");
					return;
				}
				if (batches.get(position) != null) {
					if (batches.get(position).getBatchid() != 0) {
						selectedBatch = batches.get(position).getBatchid();
					} else {
						showToast("Batchid为0");
						return;
					}

					if (batches.get(position).getMaterialfullname() != null) {
						materialName.setText(batches.get(position)
								.getMaterialfullname());
					} else {
						showToast("Materialfullname=null");
					}

					if (batches.get(position).getMaterialid() != 0) {
						materialId = batches.get(position).getMaterialid();
					} else {
						showToast("Materialid为0");
						return;
					}

				} else {
					showToast("MaterialBatch[position]为null");
					return;
				}

				batchesSec = batches.get(position).getBactchList();
				if (batchesSec != null && batchesSec.size() > 0) {
					// 如果存在二级批次，则设置选择公共（子批次）可用
					isPublicOrSec.setEnabled(true);

					String[] m = new String[batchesSec.size()];
					for (int i = 0; i < batchesSec.size(); i++) {
						m[i] = batchesSec.get(i).getBatchcode();
					}
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(
							ActivateActivity.this,
							android.R.layout.simple_spinner_item, m);
					// 设置下拉列表的风格
					adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					// 将adapter 添加到spinner中
					batchsSec.setAdapter(adapter);

					batchsSec
							.setOnItemSelectedListener(new OnItemSelectedListener() {

								@Override
								public void onItemSelected(AdapterView<?> arg0,
										View arg1, int arg2, long arg3) {
									try {
										if (batchesSec.get(arg2) != null) {
											if (batchesSec.get(arg2)
													.getBatchid() != 0) {
												selectedBatchSecId = batchesSec
														.get(arg2).getBatchid();
											} else {
												showToast("batchesSec.get(arg2).getBatchid()为0");
											}
										} else {
											showToast("batchesSec.get(position)为null");
										}
									} catch (Exception e) {
										ShowDialog("警告", e.toString());
									}

								}

								@Override
								public void onNothingSelected(
										AdapterView<?> arg0) {
									try {
										selectedBatchSecId = batchesSec.get(0)
												.getBatchid();
									} catch (Exception e) {
										ShowDialog("警告", e.toString());
									}
								}
							});
				} else {
					// 如果没有二级批次
					// 设置二级批次选择不可见，isPublic标记true，选择公共（子批次）不可用
					secLL.setVisibility(View.GONE);
					isPublic = true;
					isPublicOrSec.setSelection(0);
					isPublicOrSec.setEnabled(false);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
	}

	/*
	 * 拍起始码按钮事件
	 */
	public Button.OnClickListener startPaima = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					ActivateActivity.this);
			builder.setTitle("选择方式");
			builder.setItems(new String[] { "拍产品码", "输产品码" },
					new AlertDialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (which == 0) {
								Intent intent = new Intent(Intents.Scan.ACTION);
								startActivityForResult(intent, START);
							} else if (which == 1) {
								LayoutInflater inflater = LayoutInflater
										.from(ActivateActivity.this);
								View view = inflater.inflate(
										R.layout.dialog_edit, null);
								final EditText text = (EditText) view
										.findViewById(R.id.dialog_edittext);
								AlertDialog.Builder builder1 = new AlertDialog.Builder(
										ActivateActivity.this);
								builder1.setTitle("请输入您要拍的码号");
								builder1.setView(view);
								builder1.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												String contents = text
														.getText().toString()
														.trim();
												if (contents == null
														|| contents.equals("")) {
													Toast.makeText(
															ActivateActivity.this,
															"码内容不能为空或不符合I-OID规则",
															Toast.LENGTH_LONG)
															.show();
												} else {
													startCodStr = Utils
															.getIDcodeStr(contents);
													if (startCodStr == "") {
														Toast.makeText(
																ActivateActivity.this,
																"码内容不符合I-OID规则",
																Toast.LENGTH_LONG)
																.show();
													} else {
														startText
																.setText(contents);
													}

												}
											}
										});
								builder1.setNegativeButton("取消",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {

											}
										});
								builder1.create().show();
							}
						}
					});
			builder.create().show();

		}
	};
	/*
	 * 拍截止码按钮事件
	 */
	public Button.OnClickListener endPaima = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					ActivateActivity.this);
			builder.setTitle("选择方式");
			builder.setItems(new String[] { "拍产品码", "输产品码" },
					new AlertDialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (which == 0) {
								Intent intent = new Intent(Intents.Scan.ACTION);
								startActivityForResult(intent, END);
							} else if (which == 1) {
								LayoutInflater inflater = LayoutInflater
										.from(ActivateActivity.this);
								View view = inflater.inflate(
										R.layout.dialog_edit, null);
								final EditText text = (EditText) view
										.findViewById(R.id.dialog_edittext);
								AlertDialog.Builder builder1 = new AlertDialog.Builder(
										ActivateActivity.this);
								builder1.setTitle("请输入您要拍的码号");
								builder1.setView(view);
								builder1.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												String contents = text
														.getText().toString()
														.trim();
												if (contents == null
														|| contents.equals("")) {
													Toast.makeText(
															ActivateActivity.this,
															"码内容不能为空或不符合I-OID规则",
															Toast.LENGTH_LONG)
															.show();
												} else {

													endCodStr = Utils
															.getIDcodeStr(contents);
													if (endCodStr == "") {
														Toast.makeText(
																ActivateActivity.this,
																"码内容不符合I-OID规则",
																Toast.LENGTH_LONG)
																.show();
													} else {

														if (endCodStr.trim()
																.length() == startCodStr
																.trim()
																.length()) {

															if (Long.valueOf(endCodStr) < Long
																	.valueOf(startCodStr)) {
																Toast.makeText(
																		ActivateActivity.this,
																		"截止码应大于或等于起始码",
																		Toast.LENGTH_LONG)
																		.show();
															} else {
																// endCode =
																// contents;
																progressDialog = ProgressDialog
																		.show(ActivateActivity.this,
																				"提示",
																				"正在查询....",
																				true,
																				false);
																CodeActivationInfo caInfo = new CodeActivationInfo();
																caInfo.setStartcode(startText
																		.getText()
																		.toString()
																		.trim());
																caInfo.setEndcode(contents);
																caInfo.setEnterpriseid(enterpriseId);
																caInfo.setIsnew(isNew);

																RequestBatchsAsyn requestBatchs = new RequestBatchsAsyn(
																		contents);
																requestBatchs
																		.execute(caInfo);
															}

														} else {
															Toast.makeText(
																	ActivateActivity.this,
																	"截止码与起始码位数不同",
																	Toast.LENGTH_LONG)
																	.show();
														}
													}

												}
											}
										});
								builder1.setNegativeButton("取消",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {

											}
										});
								builder1.create().show();
							}
						}
					});
			builder.create().show();

		}
	};

	/*
	 * 激活按钮事件
	 */
	public Button.OnClickListener activateBatch = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			ActivationInfo activationInfo = new ActivationInfo();
			activationInfo.setEnterpriseid(enterpriseId);
			if (selectedBatch == 0) {
				Toast.makeText(ActivateActivity.this, "请选择批次",
						Toast.LENGTH_LONG).show();
				return;
			} else {
				activationInfo.setBatchid(selectedBatch);
			}

			if (isPublic) {
				activationInfo.setBatchidSec(-1);
			} else {
				if (selectedBatchSecId == 0) {
					Toast.makeText(ActivateActivity.this, "请选择子批次",
							Toast.LENGTH_LONG).show();
					return;
				} else {
					activationInfo.setBatchidSec(selectedBatchSecId);
				}
			}

			activationInfo.setNew(isNew);
			activationInfo.setActivationcode(requestBatchsInfo);
			activationInfo.setMaterialid(materialId);
			progressDialog = ProgressDialog.show(ActivateActivity.this, "提示",
					"正在包装附码....", true, false);
			ActivateAsyn activateAsyn = new ActivateAsyn();
			activateAsyn.execute(activationInfo);
		}
	};
	/*
	 * 返回主页按钮事件
	 */
	public Button.OnClickListener backToIndex = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			AlertDialog alert = new AlertDialog.Builder(ActivateActivity.this)
					.setTitle(getString(R.string.tip_back))
					.setCancelable(false)
					.setMessage(getString(R.string.tip_back_description))
					.setNegativeButton("否", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// do nothing
						}
					})
					.setPositiveButton("是", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// 结束应用程序
							ActivateActivity.this.finish();
						}
					}).create();
			alert.show();
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			AlertDialog alert = new AlertDialog.Builder(ActivateActivity.this)
					.setTitle(getString(R.string.tip_back))
					.setCancelable(false)
					.setMessage(getString(R.string.tip_back_description))
					.setNegativeButton("否", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// do nothing
						}
					})
					.setPositiveButton("是", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// 结束应用程序
							ActivateActivity.this.finish();
						}
					}).create();
			alert.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 拍码返回处理
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			if (requestCode == START) {

				String contents = data.getStringExtra("SCAN_RESULT").trim();
				/*
				 * String[] ss = contents.split("="); contents = ss[ss.length -
				 * 1];
				 */
				// 二维码截取
				contents = Utils.getCodeStr(contents);

				startCodStr = Utils.getIDcodeStr(contents);
				if (startCodStr == "") {
					Toast.makeText(ActivateActivity.this, "码内容不符合I-OID规则",
							Toast.LENGTH_LONG).show();
				} else {
					startText.setText(contents);
				}

				// startText.setText(contents);

			} else if (requestCode == END) {

				String contents = data.getStringExtra("SCAN_RESULT").trim();
				// 二维码截取
				contents = Utils.getCodeStr(contents);
				/*
				 * String[] ss = contents.split("="); contents = ss[ss.length -
				 * 1];
				 */

				endCodStr = Utils.getIDcodeStr(contents);
				if (endCodStr == "") {
					Toast.makeText(ActivateActivity.this, "码内容不符合I-OID规则",
							Toast.LENGTH_LONG).show();
				} else {

					if (endCodStr.trim().length() == startCodStr.trim()
							.length()) {

						if (Long.valueOf(endCodStr) < Long.valueOf(startCodStr)) {
							Toast.makeText(ActivateActivity.this,
									"截止码应大于或等于起始码", Toast.LENGTH_LONG).show();
						} else {
							// endCode = contents;
							progressDialog = ProgressDialog.show(
									ActivateActivity.this, "提示", "正在查询....",
									true, false);
							CodeActivationInfo caInfo = new CodeActivationInfo();
							caInfo.setStartcode(startText.getText().toString()
									.trim());
							caInfo.setEndcode(contents);
							caInfo.setEnterpriseid(enterpriseId);
							caInfo.setIsnew(isNew);

							RequestBatchsAsyn requestBatchs = new RequestBatchsAsyn(
									contents);
							requestBatchs.execute(caInfo);
						}

					} else {
						Toast.makeText(ActivateActivity.this, "截止码与起始码位数不同",
								Toast.LENGTH_LONG).show();
					}
				}

			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * @author Maniac
	 * @描述 根据首尾I-OID码请求批次列表
	 */
	private class RequestBatchsAsyn extends MyAsyncTask {
		CodeActivationInfo request;
		private String endcode;

		public RequestBatchsAsyn(String contents) {
			this.endcode = contents;
		}

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(ActivateActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {

				Message message = (Message) Utils.fromJSON((String) res,
						Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(ActivateActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					CodeActivationResultInfo resultInfo = (CodeActivationResultInfo) Utils
							.fromJSON(string, CodeActivationResultInfo.class);

					if (resultInfo.getResult() == 5010) {
						endText.setText(endcode);
						batches = resultInfo.getBatchList();
						if (batches == null || batches.size() == 0) {
							Toast.makeText(ActivateActivity.this, "批次列表空",
									Toast.LENGTH_LONG).show();
						} else {

							if (resultInfo.getMsg() != null
									&& !resultInfo.getMsg().equals("")) {
								ShowDialog("提示", resultInfo.getMsg());
							}

							layout.setVisibility(View.VISIBLE);
							requestBatchsInfo = request; // 只有传进请求方法的
															// 并且请求成功的才可以放入激活对象中去

							String[] m = new String[batches.size()];
							for (int i = 0; i < batches.size(); i++) {
								m[i] = batches.get(i).getBatchcode();
							}
							ArrayAdapter<String> adapter = new ArrayAdapter<String>(
									ActivateActivity.this,
									android.R.layout.simple_spinner_item, m);
							// 设置下拉列表的风格
							adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							// 将adapter 添加到spinner中
							batch.setAdapter(adapter);
						}

					} else {
						startText.setText("");
						Toast.makeText(ActivateActivity.this,
								resultInfo.getResultinfo(), Toast.LENGTH_LONG)
								.show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			request = (CodeActivationInfo) params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(5000, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}

	}

	/**
	 * @author Maniac
	 * @功能 激活选中的批次号
	 */
	private class ActivateAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(ActivateActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {
				Message message = (Message) Utils.fromJSON((String) res,
						Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(ActivateActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo) Utils.fromJSON(string,
							ResultInfo.class);
					if (resultInfo.getResult() == 5110) {
						Toast.makeText(ActivateActivity.this,
								resultInfo.getResultinfo(), Toast.LENGTH_LONG)
								.show();
						ActivateActivity.this.finish();
					} else {
						Toast.makeText(ActivateActivity.this,
								resultInfo.getResultinfo(), Toast.LENGTH_LONG)
								.show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			ActivationInfo request = (ActivationInfo) params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(5100, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}

	}
}
